package com.shaw.study.springx.webmvc;

import com.shaw.study.springx.annotation.Controller;
import com.shaw.study.springx.annotation.RequestMapping;
import com.shaw.study.springx.annotation.RequestParam;
import com.shaw.study.springx.context.ClassPathXmlApplicationContext;
import com.shaw.study.springx.context.support.ApplicationContextAware;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;

/**
 * Created by asus on 2018/4/26.
 */
public class DispatcherServlet extends HttpServlet implements ApplicationContextAware {
    private final static String LOCATION= "contextConfigLocation";
    private final static String TEMP_ROOT = "templateRoot";
    private List<HandlerMapping> handlerMappings= new ArrayList<>();
    private Map<HandlerMapping,HandlerAdapter> handlerAdapters = new HashMap<>();
    private List<ViewResolver> viewResolvers = new ArrayList<>();
    private ClassPathXmlApplicationContext applicationContext;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doDispatch(req,resp);
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        //创建上下文,
        //初始化springmvc中的所有策略
        setApplicationContext(new ClassPathXmlApplicationContext(servletConfig.getInitParameter(LOCATION)));
    }

    public void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //获取handlerMapping
        HandlerMapping handlerMapping = getHandler(req);
        if(handlerMapping==null){
            resp.getWriter().write("404 page not found");
        }
        //更具handlermapping获取adapter
        HandlerAdapter handlerAdapter = getHandlerAdapter(handlerMapping);
        //处理参数并执行方法获得返回值
        ModelAndView modelAndView = null;
        try {
            modelAndView = handlerAdapter.handle(req,resp,handlerMapping);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        //根据处理后的返回值，进行返回操作
        processDispatchResult(resp,modelAndView);
    }

    private void processDispatchResult(HttpServletResponse resp, ModelAndView modelAndView) {
        if(modelAndView==null){
            return;
        }
        String viewName = modelAndView.getViewName();
        ViewResolver viewResolver = null;
        for(ViewResolver vr:this.viewResolvers){
            if(!vr.getViewName().equals(viewName)){
                continue;
            }
            viewResolver = vr;
            break;
        }
        if(viewResolver!=null){
            String s = viewResolver.viewResolver(modelAndView);
            try {
                resp.getWriter().write(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //根据HandlerMapping获取adapter适配器
    private HandlerAdapter getHandlerAdapter(HandlerMapping handlerMapping) {
        if(this.handlerAdapters!=null&&this.handlerAdapters.size()!=0){
            return this.handlerAdapters.get(handlerMapping);
        }
        return null;
    }

    /**
     * 根据请求的路径获取handlerMapping
     * @param req
     * @return
     */
    private HandlerMapping getHandler(HttpServletRequest req) {
        if(this.handlerMappings==null||this.handlerMappings.size()==0){
            return null;
        }
        String uri = req.getRequestURI();
        uri = uri.replaceAll("/+","/");
        for(HandlerMapping handlerMapping:handlerMappings){
            Pattern pattern = handlerMapping.getUrlPattern();
            Matcher matcher = pattern.matcher(uri);
            if(!matcher.matches()){
                continue;
            }
            return handlerMapping;
        }
        return null;
    }

    protected void initStrategies(ClassPathXmlApplicationContext context) {
        //文件上传策略
        initMultipartResolver(context);
        ////本地化解析
        initLocaleResolver(context);
        //主题解析
        initThemeResolver(context);
        //用来保存requestMapping的映射关系
        initHandlerMappings(context);
        //用来处理请求参数的，包括类型转换和复制
        initHandlerAdapters(context);
        //异常处理机制
        initHandlerExceptionResolvers(context);
        //解析请求明道试图
        initRequestToViewNameTranslator(context);
        //视图模板内容的解析
        initViewResolvers(context);
        //flash映射管理
        initFlashMapManager(context);
    }

    private void initMultipartResolver(ClassPathXmlApplicationContext context) {

    }
    private void initLocaleResolver(ClassPathXmlApplicationContext context) {

    }
    private void initThemeResolver(ClassPathXmlApplicationContext context) {

    }
    private void initHandlerMappings(ClassPathXmlApplicationContext context) {
        //TODO
        String[] beanNames = context.getBeanDefinitionNames();
        for(String beanName:beanNames){
            //获取bean实例
            try{
                Object instance = context.getBean(beanName);
                //获得所有controller注解的类
                Class clazz = instance.getClass();
                //如果不是则跳过
                if(!clazz.isAnnotationPresent(Controller.class)){
                    continue;
                }
                //获得Controller的注解
                Controller controller = (Controller)clazz.getAnnotation(Controller.class);
                //获得根uri路径
                String rootUri = controller.value();
                //获得类中的所有公共方法
                Method[] methods = clazz.getDeclaredMethods();
                for(Method method:methods){
                    if(!method.isAnnotationPresent(RequestMapping.class)){
                        continue;
                    }
                    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
                    String methodUri = requestMapping.value();
                    String regex = rootUri+methodUri.replaceAll("/+","/");
                    //uri的正则匹配
                    Pattern pattern = Pattern.compile(regex);
                    //创建映射
                    HandlerMapping handlerMapping = new HandlerMapping(instance,method,pattern);
                    handlerMappings.add(handlerMapping);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    private void initHandlerAdapters(ClassPathXmlApplicationContext context) {
        for(HandlerMapping handlerMapping:handlerMappings){
            //KEY为参数在url中的名字，value为参数在method的注解参数中的位置
            Map<String,Integer> paramMap = new HashMap<String,Integer>();
            Method method = handlerMapping.getMethod();
            //获取方法中的注解参数个数，应为每个参数可以进行多个注解，所以是二位数组
            Annotation[][] paramAnnotations = method.getParameterAnnotations();
            //注解参数值的位置注册
            for(int i = 0;i<paramAnnotations.length;i++){
                for(Annotation a:paramAnnotations[i]){
                    if(a instanceof RequestParam){
                        paramMap.put(((RequestParam) a).value(),i);
                    }
                }
            }
            //非注解参数request和response
            Class<?>[] paramTypes = method.getParameterTypes();
            for(int i =0 ;i<paramTypes.length;i++){
                Class clazz = paramTypes[i];
                if(clazz==HttpServletRequest.class||clazz==HttpServletResponse.class){
                    paramMap.put(clazz.getName(),i);
                }
            }

            handlerAdapters.put(handlerMapping,new HandlerAdapter(paramMap));
        }
    }
    private void initHandlerExceptionResolvers(ClassPathXmlApplicationContext context) {
    }
    private void initRequestToViewNameTranslator(ClassPathXmlApplicationContext context) {
    }
    private void initViewResolvers(ClassPathXmlApplicationContext context) {
        //TODO
        String viewPathRoot = context.getConfig().getProperty(TEMP_ROOT);
        URL path = this.getClass().getResource("/"+viewPathRoot);

        File viewDir = new File(path.getFile());
        for(File file:viewDir.listFiles()){
            this.viewResolvers.add(new ViewResolver(file.getName(),file));
        }

    }
    private void initFlashMapManager(ClassPathXmlApplicationContext context) {
    }

    @Override
    public void setApplicationContext(ClassPathXmlApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
        initStrategies(applicationContext);
    }
}
